﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Domain.Core.ViewModel.Base;
using Domain.Model.ViewModel.Base;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace Domain.Infrastructure.Middlewares
{
    public class ExceptionHandlerMidd
    {
        private readonly RequestDelegate _next;


        public ExceptionHandlerMidd(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            if (ex == null) return;

            //TODO记录日志
            //NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.ApiRequest, "全局捕获异常", "全局捕获异常", new Exception("全局捕获异常", ex));

            await WriteExceptionAsync(context, ex).ConfigureAwait(false);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception e)
        {
            if (e is UnauthorizedAccessException)
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            else if (e is Exception)
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
            else
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;

            context.Response.ContentType = "application/json";
            var jm = new BaseResponse<Exception>();
            jm.Status = context.Response.StatusCode;
            jm.Result = e;
            jm.Message = "发生异常";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(jm)).ConfigureAwait(false);
        }
    }
}
